import React, { Component } from 'react'
import { View, Text,DeviceEventEmitter,StyleSheet,FlatList, TouchableOpacity, Image, RefreshControl  } from 'react-native'
import CollectionDao from '../../js/expand/dao/CollectionDao';
import Toast, {DURATION} from 'react-native-easy-toast'
import { LanguageDao, FLAG_LANGUAGE } from '../../js/expand/dao/LanguageDao';

export default class SearchKey extends Component {
  constructor(props) {
    super(props);
    this.collextionDao = new CollectionDao()
    this.languageDao = new LanguageDao(FLAG_LANGUAGE.flag_key)
    this.state = {
      result: [],
      loading: false,
      showBottomButton: false,
      menu: []
    }
  }

  componentWillMount() {
    DeviceEventEmitter.addListener('search', (e) => {
      // handle event.
      if(!e) {
        this.refs.toast.show('您未输入任何关键字');
        return;
      }
      this.loadData(e)
    });
  }

  loadData(name) {
    this.setState({
      loading: true
    })
    let url = 'https://api.yeshaojun.com/api/article/typelist?title='+ name
    fetch(url)
      .then((response) => response.json())
      .then((res)=> {
        this.collextionDao.checkData([...res.data]).then(result=> {
          if(!result.length) {
            this.refs.toast.show('暂未找到匹配的数据！');
          } else {
            this.languageDao.fetch().then(res => {
              let arr = [...res];
              let check = true
              arr.map(item => {
                if(item.name === name) {
                  check = false
                }
              })
              if(check) {
                arr.push({
                  "path": name,
                  "name": name,
                  "checked": true
                })
                this.setState({
                  showBottomButton: true,
                  menu: arr
                })
              }
            }).catch(err=> {
              console.log(err)
            });
          }
          this.setState({
            result: result,
            loading: false
          })
        })
      })
      .catch((error) => {
        alert(error)
      });
  }

  renderTime(time) {
    return time.split(' ')[0]
  }

  goDetail(item) {
    this.props.navigation.push('ReadDetail', {id: item.id, name: item.title, show: item})
  }

  saveKey() {
    this.languageDao.save(this.state.menu);
    this.refs.toast.show('保存成功');
  }

  renderContent(obj) {
    let str = ''
    if(obj.length>80) {
      str = obj.substring(0,80) + '......'
    } else {
      str = obj
    }
    return str;
  }

  like (item) {
    let arr = [...this.state.result];
    for(let i=0; i< arr.length; i++) {
      if(arr[i].id === item.id) {
        arr[i].show = ! arr[i].show
        // 添加
        if(arr[i].show) {
          this.collextionDao.saveData(item)
        } else {
          this.collextionDao.removeData(item)
        }
      }
    }
    this.setState({
      result: arr
    })
  }

  render () {
    let bottomButton=this.state.showBottomButton?
    <TouchableOpacity
        style={[styles.bottomButton,{backgroundColor: '#2196F3'}]}
        onPress={()=>{
            this.saveKey();
        }
        }
    >
        <View style={{justifyContent:'center'}}>
            <Text style={styles.title}>添加标签</Text>
        </View>
    </TouchableOpacity>:null;
    return <View style={styles.container}>
       <FlatList
          data={this.state.result}
          renderItem={
            ({item}) => {
              return (
                <View key={item.id} style={styles.list}>
                  <TouchableOpacity onPress={this.goDetail.bind(this, item)}>
                    <Text style={styles.title}>{item.title}</Text>
                    <Text style={styles.content}>{this.renderContent(item.introduction)}</Text>
                    <View style={{flexDirection: 'row',justifyContent: 'space-between'}}>
                      <Text style={styles.time}>{this.renderTime(item.create_time)}</Text>
                      <TouchableOpacity onPress={this.like.bind(this, item)}>
                        <Image style={styles.img} source={
                          item.show ? require('../images/ic_star.png') : require('../images/ic_unstar_transparent.png')
                        } tintColor="#2196F3"/>
                      </TouchableOpacity>
                    </View>
                  </TouchableOpacity>
                </View>
              )
            }
          }
          refreshControl ={
            <RefreshControl 
              title="Loding"
              colorRendering="red"
              colors={['red']}
              tintColor='orange'
              refreshing={this.state.loading}
              onRefresh={
                ()=> {
                  this.loadDate()
                }
              }
            />
          }
        />
        <Toast ref="toast"/>
        {bottomButton}
    </View>
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  list: {
    backgroundColor: 'white',
    padding: 10,
    marginLeft: 5,
    marginRight: 5,
    marginVertical: 3,
    borderWidth: 0.5,
    borderColor: '#ddd',
    shadowColor: 'gray',
    shadowOffset: {width: 0.5, height: 0.5},
    shadowOpacity: 0.4,
    shadowRadius: 1,
    elevation: 2
  },
  title: {
    fontSize: 14,
    color: '#333'
  },
  content: {
    paddingTop: 4,
    fontSize: 12,
    color: '#999',
    paddingRight: 30,
  },
  time: {
    paddingTop: 4,
    fontSize: 12,
    color: '#333'
  },
  img: {
    width: 20,
    height: 20
  },
  bottomButton:{
    alignItems:'center',
    justifyContent:'center',
    opacity:0.9,
    height:40,
    position:'absolute',
    left:10,
    // top:GlobalStyles.window_height-45,
    bottom: 20,
    right:10,
    borderRadius:3
  },
  centering:{
    alignItems:'center',
    justifyContent:'center',
    flex:1,
  },
})
